<template>
    <div style="width: 95%;margin: auto;">
        <!-- 
        :inline :把el-form-item 设置 行内元素
         -->
        <el-form :inline="true" :model="carFrom" class="demo-form-inline">
            <el-form-item style="width: 180px;">
                <el-input v-model="carFrom.cname" placeholder="请输入汽车名" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-select v-model="carFrom.brand" placeholder="请选择品牌" clearable>
                    <el-option label="奔驰" value="奔驰" />
                    <el-option label="宝马" value="宝马" />
                    <el-option label="保时捷" value="保时捷" />
                    <el-option label="比亚迪" value="比亚迪" />
                    <el-option label="宾利" value="宾利" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-input-number v-model="carFrom.dailyRate" :precision="2" :min="0" :step="0.01" placeholder="单日租金"
                    clearable style="width:160px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="clickfindAll(1)" style="width: 100px;">查询</el-button>
            </el-form-item>
        </el-form>
    </div>
    <!-- 卡片区域 -->
    <el-row :gutter="20" style="width:95%;margin:20px auto;">
        <el-col v-for="car in carPage.allCar" :key="car.cid" :xs="24" :sm="12" :md="6" style="margin-bottom:16px">
            <el-card shadow="hover">
                <template #header>
                    <!-- 汽车名 -->
                    <span style="font-weight:600">{{ car.cname }}</span>
                </template>
                <!-- 图片：统一高度 160px，自适应裁剪 -->
                <div style="height:160px; overflow:hidden;">
                    <el-image style="width:100%; height:100%;" :src="car.photo" fit="cover" :lazy="true" />
                </div>
                <template #footer>
                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <!-- 左侧单日租金 -->
                        <div>
                            <span style="color:#909399;font-size:12px;">单日租金: </span>
                            <span style="color:#f56c6c;font-weight:600;">{{ car.dailyRate }}</span>
                            <span style="color:#606266;font-size:12px;margin-left:2px;">元</span>
                        </div>

                        <!-- 右侧按钮 -->
                        <!-- 右侧按钮 -->
                        <div>
                            <el-button type="primary"
                                style="padding:2px 6px;height:20px;font-size:12px;line-height:1;margin-right:6px;"
                                @click="viewCar(car)">查看</el-button>

                            <el-button type="danger" style="padding:2px 6px;height:20px;font-size:12px;line-height:1;"
                                @click="rentCar(car)">租赁</el-button>
                        </div>
                    </div>
                </template>
            </el-card>
        </el-col>
    </el-row>

    <!-- 分页插件 -->
    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" v-model:page-size="carFrom.pageSize"
            v-model:current-page="carFrom.pageNum" :total="carFrom.total" @current-change="findAll" />
    </div>

    <!-- 汽车查看详情弹窗 -->
    <div v-if="showDlg" style=" position:fixed; inset:0; background:rgba(0,0,0,.5); display:flex; align-items:center; justify-content:center;
      z-index:999; " @click.self="showDlg = false">
        <!-- 2. 内容区 -->
        <div
            style=" background:#fff; border-radius:6px; width:360px; padding:16px; box-shadow:0 2px 12px rgba(0,0,0,.2); ">

            <div style="font-size:16px;font-weight:600;margin-bottom:12px;">
                车辆详情
            </div>

            <!-- 图片 -->
            <div style="height:160px;overflow:hidden;margin-bottom:12px;">
                <img :src="dlgData.photo" style="width:100%;height:100%;object-fit:cover;" />
            </div>

            <!-- 字段 -->
            <div style="font-size:14px;line-height:26px;">
                <div><span style="color:#666;">名称：</span>{{ dlgData.cname }}</div>
                <div><span style="color:#666;">型号：</span>{{ dlgData.model }}</div>
                <div><span style="color:#666;">品牌：</span>{{ dlgData.brand }}</div>
                <div><span style="color:#666;">单日租金：</span><span style="color:#f56c6c;font-weight:600;">{{
                        dlgData.dailyRate
                        }}</span> 元</div>
                <div><span style="color:#666;">剩余数量：</span>{{ dlgData.count }} 辆</div>
            </div>

            <!-- 关闭按钮 -->
            <div style="text-align:right;margin-top:12px;">
                <el-button size="small" @click="showDlg = false">关闭</el-button>
            </div>
        </div>
    </div>

    <!-- ===============  租赁弹窗（ElementPlus 版）  =============== -->
    <el-dialog v-model="rentDlg" title="租赁下单" width="400px" :close-on-click-modal="false">
        <el-form :model="rentForm" label-width="70px">
            <el-form-item label="取车日" required>
                <el-date-picker v-model="rentForm.start" type="date" :disabled-date="d => d < Date.now() - 86400000"
                    placeholder="请选择取车日" style="width:100%" />
            </el-form-item>

            <el-form-item label="还车日" required>
                <el-date-picker v-model="rentForm.end" type="date" :disabled-date="d => d <= rentForm.start"
                    placeholder="请选择还车日" style="width:100%" />
            </el-form-item>

            <el-form-item label="预计租金">
                <el-input :value="computedRent" readonly />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="rentDlg = false">取消</el-button>
            <el-button type="danger" @click="submitRent">提交订单</el-button>
        </template>
    </el-dialog>
</template>
<script setup>
//1.引入ref和reactive
import { ref, reactive, onMounted, computed } from 'vue';
import request from '../utils/request';
import { Delete, Edit, Plus, Search, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
//引入useCounterStore实例
import { useUserStore } from '../stores/userStore'
//创建stote实例
let store = useUserStore();

//存放后端查询车辆数据变量
let carPage = reactive({
    allCar: [],

})
//声明一个对象，用于条件查询
let carFrom = ref({
    pageNum: 1,
    pageSize: 8,
    total: 0,
    status: 0
})
//  汽车详情弹窗开关 + 临时数据
const showDlg = ref(false)
const dlgData = ref({})
//  查看按钮回调方法
const viewCar = (car) => {
    dlgData.value = car
    showDlg.value = true
}

//租赁弹窗需要的数据 
// 弹窗开关
const rentDlg = ref(false)
// 当前选中的车       
const currentCar = ref({})
const rentForm = reactive({
  start: '',
  end: ''
})

// 计算属性（实时显示预计租金
const computedRent = computed(() => {
  if (!rentForm.start || !rentForm.end) return '0.00'
  const days = dayjs(rentForm.end).diff(dayjs(rentForm.start), 'day')
  if (days <= 0) return '0.00'
  return (currentCar.value.dailyRate * days).toFixed(2)
})

// 租赁按钮回调方法
const rentCar = (car) => {
  currentCar.value = car
  rentForm.start = ''
  rentForm.end = ''
  rentDlg.value = true
}

//提交订单方法
const submitRent = async () => {
  if (!rentForm.start || !rentForm.end) {
    ElMessage.warning('请选择取/还车日期')
    return
  }
  const params = {
    cid: currentCar.value.cid,
    uid: store.userinfo.uid,
    startDate: dayjs(rentForm.start).format('YYYY-MM-DD'),
    endDate: dayjs(rentForm.end).format('YYYY-MM-DD'),
    dailyRate: currentCar.value.dailyRate
  }
  const res = await request.post('/orders/create', params)
  if (res.data.success) {
    ElMessage.success('下单成功')
    rentDlg.value = false
    findAll(carFrom.value.pageNum)   // 刷新列表
  } else {
    ElMessage.error(res.data.msg || '下单失败')
  }
}

//根据条件查询新闻信息
const findAll = async (currentpage) => {
    carFrom.value.pageNum = currentpage;
    let res = await request.post("/car/queryCondition", carFrom.value);
    // console.log(res);
    if (res.data.success) {
        carPage.allCar = res.data.data.list;
        carFrom.value.pageNum = res.data.data.pageNum;
        carFrom.value.pageSize = res.data.data.pageSize;
        carFrom.value.total = res.data.data.total;
        return true;
    } else {
        return false;
    }
}
//点击条件查询按钮
const clickfindAll = () => {
    if (findAll(1)) {
        ElMessage.success("查询成功")
    } else {
        ElMessage.success("查询失败")
    }
}

//当实例挂载到元素之后触发onMounted
onMounted(() => {
    //1.调用方法实现，查询用户数据
    findAll(1);
})
</script>